const db = require('../tool/db.js')
const common = require('../model/common.js')
//添加地址
async function add(data){
    let [addressExist] = await db.query('select * from address where uid = ? and address = ? and mobile = ? and name = ?',[data.id,data.address,data.mobile,data.name])
    if(addressExist.length){
        return {code:0,msg:'地址已存在',data:''}
    }
    if(data.status){
        let [defaultExist] = await db.query('update address set addrstatus = 0 where uid = ' + data.id )
        if(!defaultExist.affectedRows){
            return {code:0,msg:'添加失败请重试',data:''}
        }
    }
    
    let [res] = await db.query('insert into address (uid,address,mobile,name,addrstatus) values(?,?,?,?,?)',[data.id,data.address,data.mobile,data.name,data.status])
    if(res.insertId){
        return {code:1,msg:'添加成功',data:''}
    }
}
//删除地址
async function del(data){

    for (const i of data.id) {
        let [res] = await db.query('delete from address where uid = ? and id = ?',[data.uid,i] )
        if(!res.affectedRows){
            return {code:0,msg:'删除失败,请刷新重试',data:''}
        }
    }
    return {code:1,msg:'删除成功',data:''}
    
}
//修改地址
async function mod(data){
    if(data.addrstatus){
        let [changeStatus] = await db.query('update address set addrstatus = 0 where uid = ' + data.uid )
    
        if(!changeStatus.affectedRows){
            return {code:0,msg:'修改失败,请刷新重试',data:''}
        }
    }
    let [res] = await db.query('update address set address = ?,mobile = ? ,name = ?, addrstatus = ? where id = ? and uid = ? ',[data.newAddress,data.newMobile,data.newName,data.addrstatus,data.id,data.uid])
    if(res.affectedRows){
        return {code:1,msg:'修改成功',data:''}
    }
}
//获取用户地址
async function list(id){
    let [res] = await db.query('select address,addrstatus,id,mobile as tel,name,uid  from address where uid = ? order by addrstatus desc ',[id])
    if(res.length){
        return {code:1,msg:'成功',data:res}
    }
}
//获取默认地址
// async function defaultAddr(uid){
//     let [[res]] = await db.query('select * from address where uid = ? and addrstatus = 1',[uid])
//     if(res){
//         return {code:1,msg:'成功',data:res}
//     }
// }

module.exports ={add,del,mod,list}